<template>
  <div>
    <!-- <button @click="startGeneration">生成文档</button>  -->

    <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
        <el-form-item label="收费站" prop="deptId" v-if="deptId==101">
          <el-tree-select v-model="queryParams.deptId" :data="deptOptions" :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
            class="margin-right" placeholder="请选择部门" check-strictly clearable @change="bindChangeTree($event,'deptId')" />
        </el-form-item>
        <el-form-item label="月份" prop="month">
          <el-date-picker clearable v-model="queryParams.month" type="month" value-format="YYYY-MM" placeholder="请选择公开时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['charge:report:add']">上传</el-button>
        </el-col>

        <el-col :span="1.5">
          <!-- v-hasPermi="['charge:report:export']" -->
          <el-button type="warning" plain icon="Download" @click="downloadWord(false)" >生成</el-button>
        </el-col>

        <el-col :span="1.5">
          <el-button @click="downloadAll" icon="Bottom" type="info">批量打包下载</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['charge:report:remove']">删除</el-button>
        </el-col>

        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="reportList" @selection-change="handleSelectionChange" show-overflow-tooltip>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" width="65" align="center" label="序号" />
        <el-table-column label="月份" align="center" prop="month" v-if="deptId==101" />
        <el-table-column label="名称" align="center" prop="fileName">
          <template #default="scope">
            <el-button @click.stop="previewFun(scope.row.fileUrl)" v-if="scope.row.fileUrl">{{scope.row.fileName?scope.row.fileName:'查看'}}</el-button>
            <span v-else>暂无数据</span>
          </template>
        </el-table-column>
        <el-table-column label="上传人" align="center" prop="updateBy" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['charge:report:edit']">修改</el-button>
            <el-button link type="primary" icon="" @click="downloadWord(scope.row.month)" v-hasPermi="['charge:report:export']">下载</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['charge:report:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

      <!-- 添加或修改企务公开对话框 -->
      <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
        <el-form ref="reportRef" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="收费站" prop="deptId">
            <el-tree-select style="width: 100%;" v-model="form.deptId" :data="deptOptions" :props="{ value: 'id', label: 'label', children: 'children' }"
              value-key="id" class="margin-right" placeholder="请选择部门" check-strictly clearable />
          </el-form-item>
          <el-form-item label="月份" prop="month">
            <el-date-picker clearable style="width: 100%;" v-model="form.month" type="month" value-format="YYYY-MM" placeholder="请选择公开时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="文件名称" prop="fileName">
            <el-input v-model="form.fileName"></el-input>
          </el-form-item>
          <el-form-item label="文件" prop="fileUrl">
            <file-upload v-model="form.fileUrl" />
          </el-form-item>

        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>

      <Viewer ref="fileViewerRef" :dialog-doc="dialogDoc" />
    </div>
  </div>
</template>

<script setup>
import moment from 'moment'
import { ref } from 'vue';
import useUserStore from '@/store/modules/user'
import { getAnalysisReport } from "@/api/charge/ticket.js"
import { listReport, getReport, delReport, addReport, updateReport } from "@/api/charge/report";

import { generateWordDocument, download } from '../../../utils/wordGenerate.js';
import { deptTreeSelect } from "@/api/system/user";
import { getCKInfo } from '@/utils/auth'
import Viewer from "@/components/Custom/viewer.vue";
const { proxy } = getCurrentInstance();
let monthArr = ref(['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'])


let month = Number(moment().format('M'))
const userStore = useUserStore()
const base64Image = ref()

const generatedFile = ref(null);
// 模板文件的路径，一般放在 public 目录中
const templatePath = '/template.docx';
const data = ref({ deptName: '', "month": monthArr.value[month - 1], collectionFee: [], img1: '', img2: '', img3: '', img4: '', table: [] })

const deptName = ref()
const deptOptions = ref([])
const deptId = ref(Number(getCKInfo('deptId')))
const fileViewerRef = ref()
const dialogDoc = ref(false)
const form = ref({})
const title = ref("")
const open = ref(false)
const list = ref()
const total = ref(0)
const loading = ref(true);
const reportList = ref([])
const queryParams = ref({ "month": moment().format('YYYY-MM'), pageNum: 1, pageSize: 10, deptId: deptId.value })
const ids = ref([])
const fileList = ref([])

const startGeneration = async () => {
  try {

    generatedFile.value = await generateWordDocument(templatePath, data.value);

    download(generatedFile.value, '收费运营分析.docx');
  } catch (error) {
    console.error('Error generating document:', error);
  }
};
//文档下载
const downloadWord = () => {
  let month = queryParams.value.month ? queryParams.value.month : moment().format('YYYY-MM')
  getImageList(month)
  if (generatedFile.value) {


  } else {
    console.error('No file generated');
  }
};
/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};


const getImageList = (month) => {
  getAnalysisReport({ "deptId": deptId.value, "yearMonth": month}).then(res => {
    base64Image.value = res.data.numPie;
    data.value.collectionFee = res.data.amtTable;
    data.value.table = res.data.numTable;
    data.value.feeTable = res.data.numEnTable;
    data.value.img1 = 'data:image/png;base64,' + res.data.feeLine;
    data.value.img2 = 'data:image/png;base64,' + res.data.feePie;
    data.value.img3 = 'data:image/png;base64,' + res.data.numLine;
    data.value.img4 = 'data:image/png;base64,' + res.data.numPie;
    const monthIndex = parseInt(month.split('-')[1], 10) - 1; 
    data.value.month=monthArr.value[monthIndex];
    data.value.numEnPie = 'data:image/png;base64,' + res.data.numEnPie;
    data.value.numEnLine = res.data.numEnLine?'data:image/png;base64,' + res.data.numEnLine:'';

    
    data.value.number1 = parseFloat(res.data.amtTable[0].totalFee / 10000).toFixed(2);;
    data.value.number2 = parseFloat(res.data.amtTable[0].dayFee / 10000).toFixed(2);;
    data.value.number3 = (res.data.amtTable[3].totalFee) < 0 ? '下降' + res.data.amtTable[3].totalFee + '%' : '增长' + res.data.amtTable[3].totalFee + '%';

    data.value.number4 = res.data.amtTable[4].totalFee;
    data.value.number5 = parseFloat(res.data.amtTable[0].kFee / 10000).toFixed(2);

    data.value.number6 = res.data.kFeeRate + '%';

    data.value.number7 = (res.data.amtTable[3].kFee) < 0 ? '下降' + res.data.amtTable[3].kFee + '%' : '增长' + res.data.amtTable[3].kFee + '%';
    data.value.number8 = (res.data.amtTable[4].kFee) < 0 ? '下降' + res.data.amtTable[4].kFee + '%' : '增长' + res.data.amtTable[4].kFee + '%';
    data.value.number9 = parseFloat(res.data.amtTable[0].hFee / 10000).toFixed(2);

    data.value.number10 = res.data.hFeeRate + '%';

    data.value.number11 = (res.data.amtTable[3].hFee) < 0 ? '下降' + res.data.amtTable[3].hFee + '%' : '增长' + res.data.amtTable[3].hFee + '%';
    data.value.number12 = (res.data.amtTable[4].hFee) < 0 ? '下降' + res.data.amtTable[4].hFee + '%' : '增长' + res.data.amtTable[4].hFee + '%';



    data.value.number13 = res.data.numTable[0].totalNum;
    data.value.number14 = res.data.numTable[0].dayNum;
    data.value.number15 = (res.data.numTable[3].totalNum) < 0 ? '下降' + res.data.numTable[3].totalNum + '%' : '增长' + res.data.numTable[3].totalNum + '%';

    data.value.number16 = res.data.numTable[4].totalNum;
    data.value.number17 = res.data.numTable[0].kNum;

    data.value.number18 = res.data.kNumRate + '%';

    data.value.number19 = (res.data.numTable[3].kNum) < 0 ? '下降' + res.data.numTable[3].kNum + '%' : '增长' + res.data.numTable[3].kNum + '%';
    data.value.number20 = (res.data.numTable[4].kNum) < 0 ? '下降' + res.data.numTable[4].kNum + '%' : '增长' + res.data.numTable[4].kNum + '%';
    data.value.number21 = res.data.numTable[0].hNum;

    data.value.number22 = res.data.hNumRate + '%';

    data.value.number23 = (res.data.numTable[3].hNum) < 0 ? '下降' + res.data.numTable[3].hNum + '%' : '增长' + res.data.numTable[3].hNum + '%';
    data.value.number24 = (res.data.numTable[4].hNum) < 0 ? '下降' + res.data.numTable[4].hNum + '%' : '增长' + res.data.numTable[4].hNum + '%';


    data.value.number25 = res.data.numEnTable[0].totalNum;
    data.value.number26 = res.data.numEnTable[0].dayNum;
    data.value.number27 = (res.data.numEnTable[3].totalNum) < 0 ? '下降' + res.data.numEnTable[3].totalNum + '%' : '增长' + res.data.numEnTable[3].totalNum + '%';

    data.value.number28 = res.data.numEnTable[4].totalNum;
    startGeneration()



  })
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}


/** 查询收费运营分析列表 */
function getList() {
  loading.value = true;
  listReport(queryParams.value).then(response => {
    reportList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  fileList.value = selection.map(item => item.fileUrl);
 
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加收费运营分析";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getReport(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改收费运营分析";
  });
}
// 表单重置
function reset() {
  form.value = {
    id: null,
    deptId: deptId.value,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    fileName: null,
    fileUrl: null,
    month: null
  };
  proxy.resetForm("reportRef");
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["reportRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateReport(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addReport(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除收费运营分析编号为"' + _ids + '"的数据项？').then(function () {
    return delReport(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

const getDeptId = () => {
  userStore.getInfo().then(res => {
    if (res.code == 200) {
      deptName.value = res.user.dept.deptName;
      data.value.deptName = res.user.dept.deptName;
    }

  })
}
const downloadAll = () => {
  if (fileList.value.length == 0) {
    proxy.$modal.msgError("您还未选中数据");
    return;
  }
  proxy.download('analysis/downloadAndZip', {
    ...queryParams.value,
    filePath: fileList.value.join(',')
  }, `运营分析打包下载_${new Date().getTime()}.zip`)
}
// 预览
const previewFun = (file) => {
  const baseUrl = import.meta.env.VITE_APP_BASE_API;
  dialogDoc.value = true;
  let data = {};
  // 上传过的文件组成完成的网络路径
  if (file && file.indexOf(',') == -1) {
    data.src = `${baseUrl}${file}`;
  } else if (file && file.indexOf(',') != -1) {
    let src = file.split(',');
    let srcArr = []
    src.forEach(item => { srcArr.push(`${baseUrl}${item}`) })
    data.src = srcArr.join(',');
    file = srcArr[0]
  }

  const arr = file.split(".");
  const suffix = arr[arr.length - 1];
  if (suffix == "docx" || suffix == "doc") {
    fileViewerRef.value?.viewDocx(data, '研讨会');
  } else if (suffix == "xlsx" || suffix == "xls") {
    fileViewerRef.value?.viewXlsx(data);
  } else if (suffix == "jpg" || suffix == "jpeg" || suffix == "png") {
    fileViewerRef.value?.viewImg(data);
  } else if (suffix == "pdf") {
    fileViewerRef.value?.viewPdf(data);
  }
};
getDeptId()
getDeptTree()
getList()
</script>
